package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.activity.consult.JiuZhenFragment;
import com.hepinghospital.user.ui.activity.home.BookDoctorByDateActivity;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.CloudResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;


/**
 * 就诊室-云门诊
 * @author DELL
 */

public class DignoseOnlineFragment extends BaseFragment {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;

    MyAdapter adapter;

    List<CloudResponse> list = new ArrayList<>();


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_diagnose_online;
    }

    private static DignoseOnlineFragment dignoseOnlineFragment;

    public static DignoseOnlineFragment newInstance() {
        if (dignoseOnlineFragment == null) {
            dignoseOnlineFragment = new DignoseOnlineFragment();
        }
        return dignoseOnlineFragment;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getCloudList(UIConstants.JIUZHEN_QUERY_TYPE_0));
    }

    @Override
    public void onResume() {
        super.onResume();
        getCloudList(UIConstants.JIUZHEN_QUERY_TYPE_0);
    }

    @Override
    protected void initData() {
    }

    @OnClick({R.id.tv_consult})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_consult:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 3);
                startActivity(BookDoctorByDateActivity.class, bundle);
                break;
            default:
                break;
        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_my_ask, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (list.get(position).orderStatus == 3 || list.get(position).orderStatus == 8) {
                    if (list.get(position).canSignIn) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("cobj", list.get(position));
                        startActivity(ChatActivity.class, bundle);
                    }

                } else if (list.get(position).orderStatus == 2) {
                    if (list.get(position).readyFlag == 1) {
                        //已经报道
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("cobj", list.get(position));
                        startActivity(ChatActivity.class, bundle);
                    }

                }
            });
            holder.tv_department.setText(list.get(position).deptName);


            if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_1) {
                holder.tv_consult_type.setText(R.string.string_consult);
                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.color_grey_button_normal));

            } else if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_2) {
                holder.tv_consult_type.setText(R.string.string_referral);
                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.chooser_orange));
            }

            holder.tv_status.setText(getStatus(list.get(position).orderStatus, list.get(position).readyFlag));
            holder.tv_time.setText("预约时间:" + list.get(position).scheduleDate + " " + list.get(position).scheduleTime);
//            holder.tv_detail.setText(list.get(position).fee);
//            holder.btn_confirm.setText(list.get(position).num);
            holder.tv_name.setText(list.get(position).doctorName);
            holder.btn_confirm.setVisibility(View.VISIBLE);
            if (list.get(position).orderStatus == 3) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("进行中");
                holder.tv_detail.setText("您的远程门诊已开始，点击进入");
            } else if (list.get(position).orderStatus == 8) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("已开方");
                holder.tv_detail.setText("您的远程门诊已开方，点击进入");
            } else if (list.get(position).orderStatus == 2) {
                if (list.get(position).canSignIn) {
                    holder.btn_confirm.setBackgroundResource(R.drawable.selector_button);
                    holder.btn_confirm.setTextColor(getResources().getColor(R.color.white));
                    holder.btn_confirm.setText("报道");
                    holder.tv_detail.setText("请提前20分钟报道");
                } else {
                    holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                    holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                    holder.btn_confirm.setText("届时请来报道");
                    holder.tv_detail.setText("请提前20分钟报道");
                }
            }
            if (list.get(position).readyFlag == 1) {
                holder.btn_confirm.setBackgroundResource(R.drawable.shape_grey);
                holder.btn_confirm.setTextColor(getResources().getColor(R.color.commonGrey));
                holder.btn_confirm.setText("已报道");
                holder.tv_detail.setText("您前面还有" + list.get(position).queueNum + "人正在排队，预计还要" + list.get(position).remainTime + "分钟");
            }
            if (!UtilString.isEmpty(list.get(position).url)) {
                ImageLoaderHelper.getInstance().setCirclePicture(mContext, holder.img_head, list.get(position).url);
            } else {
                holder.img_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.img_default));
            }


            holder.btn_confirm.setOnClickListener(v -> {
                if (list.get(position).orderStatus == 2) {
                    if (list.get(position).canSignIn) {
                        setCloudReady(list.get(position).diagnoseId);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_status, tv_time, tv_detail, btn_confirm, tv_consult_type;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_status = itemView.findViewById(R.id.tv_status);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_consult_type = itemView.findViewById(R.id.tv_consult_type);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_detail = itemView.findViewById(R.id.tv_detail);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
                img_head = itemView.findViewById(R.id.img_head);
            }
        }
    }


    private String getStatus(int status, int readyFlag) {
        switch (status) {
            case 1:
                return "待支付";
            case 2:
                if (readyFlag == 1) {
                    return "已报道";
                } else {
                    return "未报道";
                }
            case 3:
                return "进行中";
            case 4:
                return "已结束";

            case 5:
                return "已取消";
            case 8:
                return "已开方";
            default:
                return "";
        }
    }


    public void getCloudList(int queryType) {
        RestProxy.getInstance().getCloudList(BaseApplication.currentUserId, "6", new Observer<List<CloudResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onNext(List<CloudResponse> cloudResponses) {
                if (queryType == UIConstants.JIUZHEN_QUERY_TYPE_1) {
//                    if (cloudResponses != null && cloudResponses.size() > 0) {
//                        JiuZhenFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_2, cloudResponses.size());
//                        JiuZhenFragment.newInstance().jumpToPage(UIConstants.JIUZHEN_TAB_POSITION_2);
//                    } else {
//                        JiuZhenFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_2, 0);
//
//                    }
                } else {
                    if (!UtilList.isEmpty(cloudResponses)) {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.VISIBLE);

                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.GONE);

                        }
                        list.clear();
                        list.addAll(cloudResponses);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.GONE);

                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.VISIBLE);

                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
//                ToastUtil.onError(getContext(), e);
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh(false);
                }
            }

            @Override
            public void onComplete() {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh(true);
                }
            }
        });
    }


    private void setCloudReady(String id) {
        RestProxy.getInstance().setCloudReady(BaseApplication.currentUserId, id, "1", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String baseResponse) {
                getCloudList(UIConstants.JIUZHEN_QUERY_TYPE_0);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(getContext(), e);
            }

            @Override
            public void onComplete() {

            }
        });
    }
}
